<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    fullscreen
    @close="emit('pushCloseDialog')"
  >
    <iframe
      :src="previewUrl"
      width="100%"
      style="padding: 0; height: calc(100vh - 58px)"
      frameborder="0"
    />
    <div class="fixed bottom-20px right-20px" v-if="filePath !== ''">
      <el-button
        type="warning"
        :loading="loading"
        icon="download"
        circle
        size="large"
        @click="exportHandler"
      >
      </el-button>
    </div>
  </el-dialog>
</template>
<script setup lang="ts" name="PreviewFileDialog">
import request from "@/utils/https/requests";
const emit = defineEmits(["pushCloseDialog"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  itemId: {
    type: String,
    default: "",
  },
  url: {
    type: String,
    default: "",
  },
  title: {
    type: String,
    default: "文件预览",
  },
});
watch(
  () => props.visible,
  (val) => {
    if (val) {
      init();
    }
    dialogVisible.value = val;
  },
  { deep: true }
);
const dialogVisible = ref(false),
  loading = ref(false),
  filePath = ref(""),
  previewUrl = ref("");
const init = () => {
  filePath.value = "";
  fetchData();
};
// 导出文件
const exportHandler = async () => {
  loading.value = true;
  request({
    url: `/${props.url}/createExportFileCode`,
    method: "post",
    data: { filePath: filePath.value },
  })
    .then((backdata: any) => {
      loading.value = false;
      window.open(
        `${import.meta.env.VITE_BASE_URL}/${props.url}/exportFileByCode/${
          backdata.data
        }`,
        "_blank"
      );
    })
    .catch(() => {
      loading.value = false;
    });
};
const fetchData = async () => {
  //   获取文件路径
  const _fileRes: any = await request({
    url: `/${props.url}/createPdfFile`,
    method: "post",
    data: { ids: [props.itemId] },
  });
  filePath.value = _fileRes.data;
  // 获取预览文件路径
  const _res: any = await request({
    url: `/${props.url}/preview`,
    method: "post",
    data: { filePath: _fileRes.data },
  });

  previewUrl.value = _res.data;
};
</script>
